package io.mft.commons.db.mapper;

import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

/**
 * Mapper接口工厂
 * 
 * @类型名称：MapperFactory
 * @说明：TODO
 * @创建者: 胡常建
 * @创建时间: 2018年3月8日 上午11:03:29
 * @修改者: 胡常建
 * @修改时间: 2018年3月8日 上午11:03:29
 */
public class MapperFactory implements FactoryBean<Object> {
	static Logger logger=LoggerFactory.getLogger(MapperFactory.class);
	private final static Map<ClassLoader, Map<String, Object>> cache = new HashMap<>();
	private Class<?> classType;

	public MapperFactory(Class<?> classType) {
		this.classType = classType;
	}

	public static Object getMapper(Class<?> mapperInterface) throws Exception {
		Map<String, Object> map=cache.get(mapperInterface.getClassLoader());
		if (map==null) {
			synchronized (cache) {
				map=cache.get(mapperInterface.getClassLoader());
				if (map==null) {
					map=new HashMap<>();
					cache.put(mapperInterface.getClassLoader(), map);
				}
			}
		}
		Object object = map.get(mapperInterface.getName());
		if (object==null) {
			synchronized (cache) {
				object = map.get(mapperInterface.getName());
				if (object==null) {
					object=instance(mapperInterface);
					map.put(mapperInterface.getName(), object);
				}
				return object;
			}
		}else {
			return object;
		}
	}

	private static Object instance(Class<?> classType) {
		MapperProxy mapperProxy = new MapperProxy();
		Object object = Proxy.newProxyInstance(classType.getClassLoader(), new Class[] { classType },mapperProxy);
		//logger.warn("实例化数据接口Mapper:" + classType.getName());
		return object;
	}
	@Override
	public Object getObject() throws Exception {
		return getMapper(classType);
	}

	@Override
	public Class<?> getObjectType() {
		return classType;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
}
